package com.mvc.demo.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.i18n.LocaleChangeInterceptor;
import org.springframework.web.servlet.i18n.SessionLocaleResolver;

import java.util.Locale;

/**
 * @author H
 * @date 2023/1/8
 */
@Configuration
public class I18nConfig implements WebMvcConfigurer {
    private LocaleChangeInterceptor localeChangeInterceptor;

    /**
     * 国际化解析器，注意：这个Bean name要为localeResolver,这是Spring MVC中的约定，否则系统就不会感知这个解析器
     * @return
     */
    @Bean("localeResolver")
    public LocaleResolver initLocaleResolver() {
        SessionLocaleResolver sessionLocaleResolver = new SessionLocaleResolver();
        // 默认国际化区域
        sessionLocaleResolver.setDefaultLocale(Locale.SIMPLIFIED_CHINESE);
        return sessionLocaleResolver;
    }

    /**
     * 创建国际化拦截器（通过请求参数来让用户自定义国际化）
     * @return
     */
    @Bean
    public LocaleChangeInterceptor localeChangeInterceptor() {
        if (localeChangeInterceptor != null) {
            return localeChangeInterceptor;
        }
        localeChangeInterceptor = new LocaleChangeInterceptor();
        // 设置参数名(默认参数名是locale)
        // localeChangeInterceptor.setParamName("language");
        return localeChangeInterceptor;
    }

    /**
     * 给处理器增加国际化拦截器
     * @param registry
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // 这里将通过国际化拦截器的preHandle方法对请求的国际化区域参数进行修改
        registry.addInterceptor(localeChangeInterceptor());
    }
}
